/// <license>
/// Copyright (c) 2002-2008, DotNetNuke Corporation
/// All rights reserved
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
/// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
/// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
/// of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
/// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
/// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
/// DEALINGS IN THE SOFTWARE.
/// </license>

#region Using Statements

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;

using DotNetNuke.Modules.Articles.Common;
using Constants = DotNetNuke.Modules.Articles.Common.Constants;
using DotNetNuke.Modules.Articles.Framework;

#endregion

namespace DotNetNuke.Modules.Articles.UI.Controls
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The SectionsCombo skin object provides a Sections Drop Down List
    /// </summary>
    /// <history>
    /// 	[cnurse]	02/01/2006	created
    /// </history>
    /// -----------------------------------------------------------------------------
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
    ToolboxData("<{0}:SectionsCombo runat=\"server\"> </{0}:SectionsCombo>")]
    public class SectionsCombo : CollectionSkinObjectBase, IPostBackDataHandler 
    {

        #region Private Members

        private List<SectionInfo> DisplaySections = new List<SectionInfo>();

        #endregion

        #region Protected Properties

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the sections associated with the control
        /// </summary>
        /// <history>
        /// 	[cnurse]	03/21/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected List<SectionInfo> Sections
        {
            get
            {
                List<SectionInfo> _Sections = new List<SectionInfo>();
                if (ParentArticlesModule != null)
                    _Sections = ParentArticlesModule.Sections;
                return _Sections;
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        #endregion

        #region Private Methods

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderSection renders a single Section
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <param name="section">The section to Render</param>
        /// <param name="rowIndex">The index of the section in the collection</param>
        /// <history>
        /// 	[cnurse]	03/21/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void RenderSection(HtmlTextWriter writer, SectionInfo section, int rowIndex)
        {
            //Add the Value Attribute
            writer.AddAttribute(HtmlTextWriterAttribute.Value, section.SectionId.ToString());
            
            //Add the selected Attribute
            if (section.SectionId == SectionId)
                writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected");

            //Render Option Tag
            writer.RenderBeginTag(HtmlTextWriterTag.Option);

            writer.Write(section.Name);

            //Render end of Option Tag
            writer.RenderEndTag();

        }

        #endregion

        #region Protected Methods

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
            base.AddAttributesToRender(writer);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// OnPreRender runs just before the rendering phase
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="e">An EventArgs object</param>
        /// <history>
        /// 	[cnurse]	03/30/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (DesignMode)
            {
                SectionInfo section;
                for (int i = 0; i < 5; i++)
                {
                    section = new SectionInfo();
                    section.Name = "Section " + i.ToString();
                    DisplaySections.Add(section);
                }
            }
            else
            {
                for (int i = StartIndex; i < Sections.Count; i++)
                    DisplaySections.Add(Sections[i]);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderContents renders the contents of the control
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	03/18/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void RenderContents(HtmlTextWriter writer)
        {
            //Render the Caption
            RenderCaption(writer);

            //Render the Select Tag
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
            writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackEventReference(this, String.Empty));
            writer.RenderBeginTag(HtmlTextWriterTag.Select);

            //Render a row for each Section
            int rowIndex = 0;
            foreach (SectionInfo section in DisplaySections)
            {
                RenderSection(writer, section, rowIndex);
                rowIndex++;
            }

            //Render end of Select Tag
            writer.RenderEndTag();

            //Render Edit Button
            if (this.ParentArticlesModule.IsEditMode)
                RenderViewButton(writer, ParentArticlesModule.ArticleURL(TabId, Null.NullInteger, SectionId, Constants.KEY_ViewSection, true));
            else
                RenderEditButton(writer, ParentArticlesModule.ArticleURL(TabId, Null.NullInteger, SectionId, Constants.KEY_EditSection, true));

            //Display Add Button
            string url = ParentArticlesModule.ArticleURL(TabId, Null.NullInteger, SectionId, Constants.KEY_AddSection, true);
            RenderAddButton(writer, url, true);

        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Render renders the control
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	03/22/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void Render(HtmlTextWriter writer)
        {
            if (Page != null)
                Page.VerifyRenderingInServerForm(this);

            base.Render(writer);
        }

        #endregion

        #region IPostBackDataHandler Members

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// LoadPostData loads the Post Back Data and determines whether the selected
        /// Section has changed
        /// </summary>
        /// <param name="postDataKey">A key to the PostBack Data to load</param>
        /// <param name="postCollection">A name value collection of postback data</param>
        /// <history>
        ///     [cnurse]	03/22/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            bool dataChanged = false;
            int presentValue = SectionId;
            int postedValue = Int32.Parse(postCollection[postDataKey]);
            if (!presentValue.Equals(postedValue))
            {
                SectionId = postedValue;
                dataChanged = true;
            }
            return dataChanged;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RaisePostDataChangedEvent runs when the PostBackData has changed.  It triggers
        /// a SectionChanged Event
        /// </summary>
        /// <history>
        ///     [cnurse]	03/22/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void RaisePostDataChangedEvent()
        {
            //Redirect to new section
            string redirectUrl;
            if (this.ParentArticlesModule.IsEditMode)
                redirectUrl = ParentArticlesModule.ArticleURL(TabId, Null.NullInteger, SectionId, Constants.KEY_EditSection, true);
            else
                redirectUrl = ParentArticlesModule.ArticleURL(TabId, Null.NullInteger, SectionId, Constants.KEY_ViewSection, true);

            this.Context.Response.Redirect(redirectUrl, true);
        }

        #endregion

    }
}
